package org.dxy.infrastructure.persistent.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.query.MPJLambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.stereotype.Service;
import org.dxy.infrastructure.entity.DomainEventEntity;
import org.dxy.infrastructure.persistent.mapper.DomainEventMapper;
import org.dxy.infrastructure.persistent.service.DomainEventService;

import java.util.List;

/**
 * 领域事件服务实现类
 * @author dxy
 */
@Service
public class DomainEventServiceImpl extends MPJBaseServiceImpl<DomainEventMapper, DomainEventEntity> implements DomainEventService {

    @Override
    public Integer findMaxIndexByAggregateId(Long aggregateId) {

        // 使用 MPJLambdaQueryWrapper 查询最大 index
        MPJLambdaQueryWrapper<DomainEventEntity> queryWrapper = new MPJLambdaQueryWrapper<>();
        queryWrapper.select(DomainEventEntity::getEventIndex)
                .eq(DomainEventEntity::getAggregateId, aggregateId)
                .orderByDesc(DomainEventEntity::getEventIndex)
                .last("LIMIT 1"); // 限制返回一条记录以优化性能

        // 执行查询
        DomainEventEntity entity = this.getOne(queryWrapper);
        // 返回结果，处理空值情况
        return entity != null ? entity.getEventIndex() : null;
    }

    @Override
    public List<DomainEventEntity> getEventListByAggregateId(Long workOrderId) {
        MPJLambdaQueryWrapper<DomainEventEntity> queryWrapper = new MPJLambdaQueryWrapper<>();
        queryWrapper.selectAll(DomainEventEntity.class)
                .eq(DomainEventEntity::getAggregateId, workOrderId)
                .orderByAsc(DomainEventEntity::getEventIndex);
        return this.list(queryWrapper);
    }

    @Override
    public boolean markEventsPublished(List<Long> eventIds) {
        if (eventIds == null || eventIds.isEmpty()) {
            throw new IllegalArgumentException("eventIds 不能为空");
        }

        LambdaUpdateWrapper<DomainEventEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(DomainEventEntity::getPublished,true)
                .eq(DomainEventEntity::getPublished, false)
                .in(DomainEventEntity::getId,eventIds);
        return this.update(lambdaUpdateWrapper);
    }
}